//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package triger_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MsgIndexDbItem struct {
	RecordId  string   `bson:"_id"`
	MsgId     string   `bson:"msgId"`
	TrigerId  string   `bson:"trigerId"`
	TimeStamp int64    `bson:"timeStamp"`
	AttrList  []string `bson:"attrList"`
}

func GenMsgRecordId(trigerId, msgId string) string {
	return fmt.Sprintf("%s:%s", trigerId, msgId)
}

type _MsgIndexDao struct {
	mc *mongo.Collection
}

func newMsgIndexDao(db *mongo.Database) (*_MsgIndexDao, error) {
	mc := db.Collection(db_ns.DB_NS_TRIGER + "msg_index")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"trigerId", 1}, {"attrList", 1}, {"timeStamp", 1}},
		},
		{
			Keys: bson.D{{"trigerId", 1}, {"timeStamp", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_MsgIndexDao{mc: mc}, nil
}

func (db *_MsgIndexDao) Insert(ctx context.Context, dbItem *MsgIndexDbItem) error {
	dbItem.RecordId = GenMsgRecordId(dbItem.TrigerId, dbItem.MsgId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_MsgIndexDao) RemoveByTriger(ctx context.Context, trigerId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"trigerId": trigerId})
	return err
}

func (db *_MsgIndexDao) Count(ctx context.Context, trigerId string, filterByAttr bool, attrList []string) (uint32, error) {
	query := bson.M{"trigerId": trigerId}
	if filterByAttr {
		query["attrList"] = bson.M{"$all": attrList}
	}

	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_MsgIndexDao) Get(ctx context.Context, trigerId, msgId string) (*MsgIndexDbItem, error) {
	recordId := GenMsgRecordId(trigerId, msgId)
	retItem := &MsgIndexDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": recordId}).Decode(retItem)
	return retItem, err
}

func (db *_MsgIndexDao) List(ctx context.Context, trigerId string, filterByAttr bool, attrList []string, offset, limit int64) ([]*MsgIndexDbItem, error) {
	query := bson.M{"trigerId": trigerId}
	if filterByAttr {
		query["attrList"] = bson.M{"$all": attrList}
	}

	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}

	retList := []*MsgIndexDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
